/*
 *@Description: 数据库注入字典数据
 *@Author: panlua
 *@Date: 2019-05-22 11:03:24
*/
const consola = require('consola')
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const fs = require('fs')
const config = require('../dbs/config')
const connection = mongoose.connection;
// 连接数据库
mongoose.connect(config.dataBase.dbs, {useNewUrlParser: true});

connection.on('connected', () => {
  consola.success({
    message: '数据库连接成功',
    badge: true
  })
})

// 定义字典模型
const dicSchema = new Schema({
  dicType: { // 字典类型
    type: String,
    required: true
  },
  value: { // 枚举值
    type: Number, 
    required: true
  },
  label: { // 显示名称
    type: String,
    required: true
  },
  description: { // 描述
    type: String,
    required: true
  },
  status: { // 启用状态  true：启用 false：禁用
    type: Boolean,
    required: true
  }
})

// 创建 dicModel
const DIC = mongoose.model('Dic', dicSchema, 'dic')

// 读取字典json
fs.readFile('./dic.json', async(err, data) => {
  if (err) consola.success('字典JSON读取失败：' + err)
  const dicData = await JSON.parse(data.toString())
  await DIC.deleteMany('', err => {
    if (err) return consola.error('dic字典清空失败：' + err)
    consola.success({
      message: 'dic字典清空成功',
      badge: true
    })
  })
  await DIC.insertMany(dicData, err => {
    if (err) return consola.error('dic字典写入数据库失败：' + err)
    consola.success({
      message: 'dic字典写入数据库成功',
      badge: true
    })
  })
})